package com.cloud.wms.http.interceptor;

import android.util.Log;


import com.cloud.wms.http.url.SiteHeader;
import com.cloud.wms.http.url.SiteManager;
import com.cloud.wms.http.url.SiteNameEnum;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;


/**
 * Created by Tanghaibo
 * 2018/3/22
 * description: 请求拦截器 为请求添加请求头信息
 */

public class RequestInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String method = request.method();
        String requestContent;
        if ("POST".equals(method) && request.body() != null) {  //请求方法为POST，请求体不为空 获取请求body内容
            RequestBody body = request.body();
            Buffer buffer = new Buffer();
            body.writeTo(buffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = body.contentType();
            if (contentType != null) {
                charset = contentType.charset(Charset.defaultCharset());
            }
            requestContent = buffer.readString(charset);
        } else {                                                   //获取url后拼接的请求参数
            String url = request.url().toString();
            int index = url.indexOf("?");
            requestContent = url.substring(index + 1);
        }
        Log.e("body", requestContent);
        //获取request的创建者builder
        Request.Builder builder = request.newBuilder();
        //从request中获取headers，通过给定的键url_name
        List<String> headerValues = request.headers(SiteHeader.SITE_HEADER_NAME);
        if ((headerValues != null && headerValues.size() > 0)) {
            //如果有这个header，先将配置的header删除，因此header仅用作app和okhttp之间使用
            builder.removeHeader(SiteHeader.SITE_HEADER_NAME);
            //匹配获得新的BaseUrl
            String headerValue = headerValues.get(0);
            request = SiteManager.getSignHeader(request);
        } else {
            request = SiteManager.getSignHeader(request);
        }
        return chain.proceed(request);
    }
}
